package cn.taoshop.user.action;



import java.io.IOException;
import java.util.Date;

import javax.mail.Session;
import javax.persistence.Column;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpRequest;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;

import cn.taoshop.user.service.UserService;
import cn.taoshop.user.vo.User;
import cn.taoshop.utils.MailUtil;
import cn.taoshop.utils.UUIDUtils;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sun.jmx.snmp.Timestamp;
import com.sun.org.apache.xpath.internal.operations.And;

// 用户模块Action的类
 
public class UserAction extends ActionSupport implements ModelDriven<User> {
	

	// 模型驱动使用的对象
	private User user = new User();
	
	public User getModel() {
		return user;
	}
  
	// 接收验证码:
	private String checkcode;
	

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	// 注入UserService
	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	private String sid;	//
	public String getSid() {
		return sid;
	}

	public void setSid(String sid) {
		this.sid = sid;
	}
	private String userName;
	
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String registPage() {
		
		return "registPage";
	}

	// AJAX进行异步校验用户名的执行方法
	
	public String findByName() throws IOException {
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		
		// 调用Service进行查询:
		User existUser = userService.findByUsername(user.getUsername());
		// 获得response对象,向页面输出:
		
		// 判断
		if(user.getUsername().equals("")){
			response.getWriter().println("<font color='red'>用户名不能为空</font>");
			return NONE;
		}
		if (existUser != null) {
			// 查询到该用户:用户名已经存在
			response.getWriter().println("<font color='red'>用户名已经存在</font>");
		} else {
			// 没查询到该用户:用户名可以使用
			response.getWriter().println("<font color='green'>用户名可以使用</font>");
		}
		return NONE;
	}
	

	//AJAX异步查询email
	public String checkEmail() throws IOException{
		
		int count = userService.checkEmail(user.getEmail(),1);  //对比已激活用户的email
		//获得response对象，向页面输出
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		
		if(user.getEmail().equals("")) {
			response.getWriter().println("<font color='red'>邮箱不能为空</font>");
			return NONE;
		}
		else if(count > 0){
			response.getWriter().println("<font color='red'>邮箱已注册</font>");
		}
		return NONE;
	}

	// 用户注册的方法:
	 
	public String regist(){
		
		User existUser = userService.findByUsername(user.getUsername());
		
		int count = userService.checkEmail(user.getEmail(),1);  //对比已激活用户的email
		// 从session中获得验证码的随机值:
		String checkcode1 = (String) ServletActionContext.getRequest()
				.getSession().getAttribute("checkcode");
		
		if(!checkcode.equalsIgnoreCase(checkcode)){//里面的改checkcode2
			this.addActionMessage("验证码输入错误!");
		
			return "checkcodeFail";
		}else if(count > 0){
			this.addActionMessage("邮箱已注册，请重新输入！");
			return "checkcodeFail";
		}else if(existUser != null){
			this.addActionMessage("用户名已存在，请重新输入！");
			return "checkcodeFail";
		} else{
			user.setIs_del(0);
			userService.save(user);
			
			this.addActionMessage("注册成功!请去邮箱激活!");
			return "msg";
		}
			
	}

	// 用户激活的方法
	
	public String active() {
		// 根据激活码查询用户:
		if(sid.equals("") || userName.equals("")){
			this.addActionMessage("链接不完整，请重新生成");
			return "msg";
		}
		User existUser = userService.findByUsername(userName);
		// 判断
		if (existUser != null) {
			
			
			if(existUser.getOutdate().getTime() <= System.currentTimeMillis()){
				this.addActionMessage("链接已过期！请重新生成");
				return "msg";
			}
			System.out.println("name:"+existUser.getUsername()+"|outdate:"+existUser.getOutdate()+"|code:"+existUser.getCode());
			String key = existUser.getUsername()+"$"+existUser.getCode();
			String digitalSignature = DigestUtils.md5DigestAsHex(key.getBytes());// 数字签名
			if(!digitalSignature.equals(sid)){
				this.addActionMessage("链接不正确！请重新生成");
				return "msg";
			} else{
				// 激活成功
				// 修改用户的状态
				existUser.setState(1);
				existUser.setCode(null);
				userService.update(existUser);
				this.addActionMessage("激活成功:请去登录!");
				return "msg";
			}
		
		} else{
			this.addActionMessage("链接错误，无法找到匹配用户！");
			return "msg";
		}
	}
	public String findpwdPage(){
		
		return "findpwdPage";
	}
	
	//找回密码
	public String findPwd(){
		User existUser = userService.findByUsername(userName);
		int count = userService.checkEmail(user.getEmail(),1); //对已激活用户查询邮箱
		String checkcode3 = (String) ServletActionContext.getRequest()
				.getSession().getAttribute("checkcode");
		if(!checkcode.equalsIgnoreCase(checkcode)){//里面的改checkcode2
			this.addActionMessage("验证码输入错误!");
			return "message";
		}
		if( existUser == null || count == 0){
			this.addActionMessage("用户或邮箱不存在！");
			return "message";
		}else{
			String code = UUIDUtils.getUUID()+UUIDUtils.getUUID();
			existUser.setCode(code);
			long outDate = (System.currentTimeMillis() + 30 * 60 * 1000)/1000 * 1000;// 30分钟后过期
	        Date date = new Date(outDate);
	        existUser.setOutdate(date);
			userService.update(existUser);
			String key = existUser.getUsername()+"$"+existUser.getCode();
			String digitalSignature = DigestUtils.md5DigestAsHex(key.getBytes());// 数字签名
			String path = ServletActionContext.getRequest().getContextPath();
			String basePath =ServletActionContext.getRequest().getScheme()+"://"
					+ServletActionContext.getRequest().getServerName()+":"
					+ServletActionContext.getRequest().getServerPort()+path+"/";
			String resethref = basePath+"user_checkLink.action?sid="+
					digitalSignature+"&userName="+existUser.getUsername();
			
			
			String subject="找回您的密码";
			String emailContent="请勿回复本邮件，点击下面链接，重设密码<br/><a href="
					+resethref+" target='_BLANK'>点击我重新设置新密码</a>"+resethref+"</a>"+"<br/>tips:本邮件超过30分钟，链接将会失效！";
			// 发送激活邮件;
			MailUtil.sendMail(existUser.getEmail(),subject,emailContent);
			this.addActionMessage("重置密码邮件已经发送，请登陆邮箱进行重置！");
			return "msg";
		}
		
	}
	//重置密码
	public String resetPwd(){
		userService.updatePwd(user);
		this.addActionMessage("密码已修改成功！");
		return "msg";
	}
	
	//找回密码链接验证
	public String checkLink(){
		if(sid.equals("") || userName.equals("")){
			this.addActionMessage("链接不完整，请重新生成");
			return "msg";
		}
		User existUser = userService.findByUsername(userName);
		// 判断
		if (existUser != null) {
			
			
			if(existUser.getOutdate().getTime() <= System.currentTimeMillis()){
				this.addActionMessage("链接已过期！请重新生成");
				return "msg";
			}
			
			String key = existUser.getUsername()+"$"+existUser.getCode();
			String digitalSignature = DigestUtils.md5DigestAsHex(key.getBytes());// 数字签名
			if(!digitalSignature.equals(sid)){
				this.addActionMessage("链接不正确！请重新生成");
				return "msg";
			} else{
				
				
				userService.update(existUser);
				return "resetpwdPage";
			}
		
		} else{
			this.addActionMessage("链接错误，无法找到匹配用户！");
			return "msg";
		}
	}

	// 跳转到登录页面
	 
	public String loginPage() {
		
		User existUser = (User)ServletActionContext.getRequest()
				.getSession().getAttribute("existUser");
		
		if(existUser != null){
			
			return "index";
		}
		return "loginPage";
	}

	// 登录的方法
	 
	public String login() {
		User existUser = userService.login(user);
		int state = 0; //0:未激活，1：用户名密码不正确
		state = userService.checkuserstate(user);
		String checkcode2 = (String) ServletActionContext.getRequest()
				.getSession().getAttribute("checkcode");
		// 判断
		System.out.println(checkcode2+"|");
		System.out.println(checkcode);
		if(!checkcode.equalsIgnoreCase(checkcode)){	//要改为checkcode2
			this.addActionError("验证码输入错误!");
			return LOGIN;
		}
		else if (state == -1) {
			// 登录失败
			this.addActionError("登录失败:用户名或密码错误!");
			return LOGIN;
		}else if (state == 0) {
			this.addActionError("用户未激活");
			return LOGIN;
		} 
		 else{
			// 登录成功
			// 将用户的信息存入到session中
			ServletActionContext.getRequest().getSession()
					.setAttribute("existUser", existUser);
			// 页面跳转
			return "loginSuccess";
		}
	
	}
	
	// 用户退出的方法
	
	public String quit(){
		// 销毁session
		
		ServletActionContext.getRequest().getSession().invalidate();
		return "quit";
	}


	}	
